package View;

import Dao.User;
import Dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf-8");

        // 1. 获取输入的用户名和密码
        String username = req.getParameter("username");
        String password1 = req.getParameter("password1");
        String password2 = req.getParameter("password2");
        // 2. 如果有一个为空就注册失败
        if (username == null || password1 == null || password2 == null || "".equals(username) || "".equals(password1) || "".equals(password2)) {
            resp.getWriter().write("<h3>输入有误!注册失败!</h3>");
            return;
        }
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        // 如果user不为空.表示有人注册了
        if(user!=null){
            resp.getWriter().write("<h3>用户名已经被使用了</h3>");
            return;
        }
        // 如果两次密码不一致注册失败
        if(!password1.equals(password2)){
            resp.getWriter().write("<h3>两次输入的密码不一致,注册失败!");
            return;
        }
        // 这里就注册成功了
        User user1 = new User();
        user1.setUserName(username);
        user1.setPassWord(password1);
        userDao.insert(user1);

        resp.sendRedirect("login.html");
    }
}
